package cn.jee.controller;

import cn.jee.entity.Mentee;
import cn.jee.repository.AdvisorRepository;
import cn.jee.repository.MenteeRepository;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
@AllArgsConstructor
public class MenteeActions {
  private  final  MenteeRepository menteeRepository;
  private  final AdvisorRepository advisorRepository;

  @PostMapping("/saveMentee")
  public String saveMentee(@Valid Mentee mentee,
                           BindingResult result,
                           @RequestParam("avatarFile") MultipartFile file,
                           Model model) {
    if (result.hasErrors()) {
      model.addAttribute("mentee", mentee);
      return "mentee_form";
    }

    if (!file.isEmpty()) {
      try {
        String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        File dest = new File("d:/" + filename);
        file.transferTo(dest);
        mentee.setAvatarFileName(filename);
      } catch (IOException e) {
        throw new RuntimeException("头像上传失败：" + e.getMessage());
      }
    }

    menteeRepository.save(mentee);
    return "redirect:/";
  }
  @GetMapping("/mentee/create")
  public String showMenteeForm(Model model) {
    model.addAttribute("mentee", new Mentee());
    return "mentee_form";
  }


}
